from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse

from wepapi.models import PrettyNum
from wepapi.utils.Pagination import Pagination
from wepapi.utils.form import PrettyNumForm,PrettyEditNumForm


def pretty_list(request):
    data_dict = {}
    search_data = request.GET.get("q", '')
    if search_data:
        data_dict["mobile__contains"] = search_data

    queryset = PrettyNum.objects.all().order_by('-level').filter(**data_dict)
    page_object = Pagination(request, queryset)

    context = {
        "search_data": search_data,
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 页码
    }

    return render(request, "pretty_list.html", context)
    # page = int(request.GET.get("page", 1))
    # page_size = 10  # 每页显示10条数据
    # start = (page - 1) * page_size
    # end = page * page_size
    #
    # model_list = PrettyNum.objects.all().order_by('-level')[page_object.start:page_object.end]
    # # 数据总条数
    # total_ocunt = PrettyNum.objects.all().order_by('-level').count()
    # # 总页面
    # total_page_ocunt, div = divmod(total_ocunt, page_size)
    # if div:
    #     total_page_ocunt += 1
    # # 计算出，显示当前页的前五页、后五页
    # plus = 5
    # if total_page_ocunt <= 2 * plus + 1:
    #     start_page = 1
    #     end_page = total_page_ocunt
    # else:
    #     # 数据库中的数据比较多 大雨11页面
    #     # 当前页面小于5时(小极值)
    #     if page <= plus:
    #         start_page = 1
    #         end_page = 2 * plus + 1
    #     else:
    #         # 当前页大于 5
    #         if (page + plus) > total_page_ocunt:
    #             start_page = total_page_ocunt - 2 * plus
    #             end_page = total_page_ocunt
    #         else:
    #             start_page = page - plus
    #             end_page = page + plus
    # # 页码
    # page_str_list = []
    # page_str_list.append('<li class="page-item"><a class="page-link" href="?page=1">首页</a></li>'.format(1))
    # # 上一页
    # if page > 1:
    #     prev = '<li class="page-item"><a class="page-link" href="?page={}">上一页</a></li>'.format(page - 1)
    # else:
    #     prev = '<li class="page-item"><a class="page-link" href="?page={}">上一页</a></li>'.format(1)
    # page_str_list.append(prev)
    # # 页面
    # for i in range(start_page, end_page + 1):
    #     if i == page:
    #         ele = '<li class="active"><a class="page-link" href="?page={}">{}</a></li>'.format(i, i)
    #     else:
    #         ele = '<li class="page-item"><a class="page-link" href="?page={}">{}</a></li>'.format(i, i)
    #     page_str_list.append(ele)
    # # 下一页
    # if page < total_page_ocunt:
    #     prev = '<li class="page-item"><a class="page-link" href="?page={}">下一页</a></li>'.format(page + 1)
    # else:
    #     prev = '<li class="page-item"><a class="page-link" href="?page={}">下一页</a></li>'.format(1)
    # page_str_list.append(prev)
    #
    # page_str_list.append(
    #     '<li class="page-item"><a class="page-link" href="?page={}">尾页</a></li>'.format(total_page_ocunt))
    # page_string = mark_safe("".join(page_str_list))

    # 分页数据
    # PrettyNum.objects.all().order_by('-level')[0:10]
    # PrettyNum.objects.all().order_by('-level')[10:20]
    # PrettyNum.objects.all().order_by('-level').count()
    # for i in range(200):
    #     PrettyNum.objects.create(mobile="13896318700", price=10 + i, level=1, status=1)
    # """获取靓号列表"""
    # if request.method == "POST":
    #     """
    #         ##数字###
    #      PrettyNum.objects.filter(id=12)         # 等于12
    #      PrettyNum.objects.filter(id__gt=12)     # 大于12
    #      PrettyNum.objects.filter(id__gte=12)    # 大于等于12
    #      PrettyNum.objects.filter(id__lt=12)     # 小于12
    #      PrettyNum.objects.filter(id__lte=12)    # 小于等于12
    #
    #       ##字符串###
    #      PrettyNum.objects.filter(mobile ="1999")                 # 等于
    #      PrettyNum.objects.filter(mobile__startswith ="1999")     # 筛选出以1999开头
    #      PrettyNum.objects.filter(mobile__endswith ="1999")       # 筛选出以1999结尾
    #      PrettyNum.objects.filter(mobile__contains ="1999")       # 筛选出包含1999
    #      """
    #     mobile = request.POST.get("mobile")
    #     if mobile:
    #         # model_list = model_list.filter(mobile__icontains=mobile)
    #         model_list = queryset.filter(mobile__contains=mobile)


# def pretty_list1(request):


# class PrettyNumForm(BootStrapModelForm):
#     # # 对提交的字段验证方式1：
#     mobile = forms.CharField(
#         # 字段
#         label="手机号码",
#         # 正则表达式（1开头，再只能3-9里面选择，后面只能9个数，报错）
#         validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
#     )
#
#     # price = forms.CharField(min_length=1, label="价格")
#     # level = forms.CharField( label="级别")
#     # status = forms.CharField( label="状态")
#
#     class Meta:
#         model = PrettyNum
#         # 获取字段
#         fields = "__all__"  # 所有字段
#         # fields = ["mobile", "price", "level", "status"]
#         # exclude = ["price"]       # 排除字段其余的都显示
#
#     #
#     # def __init__(self, *args, **kwargs):
#     #     super().__init__(*args, **kwargs)
#     #     for name, field in self.fields.items():
#     #         field.widget.attrs = {
#     #             'class': 'form-control',
#     #             'placeholder': '请输入' + field.label,
#     #         }
#
#     def clean_mobile(self):
#         mobile = self.cleaned_data.get('mobile')
#         if len(mobile) != 11:
#             # 验证不通过
#             raise ValidationError('格式错误')
#         if PrettyNum.objects.filter(mobile=mobile).exists():
#             raise forms.ValidationError("该手机号码已存在。")
#         return mobile
#
#     # 对提交的字段验证方式2：
#     # def clean_mobile(self):
#     #     txt_moble = self.cleaned_data["mobile"]
#     #     if len(txt_moble) != 11:
#     #         # 验证不通过
#     #         raise ValidationError('格式错误')
#     #     # 验证通过
#     #     return txt_moble
#
#
# class PrettyEditNumForm(forms.ModelForm):
#     """
#     mobile = forms.CharField(disabled=True, label="手机号码")
#     disabled=True 不可编辑
#     """
#     mobile = forms.CharField(disabled=True, label="手机号码")
#
#     class Meta:
#         model = PrettyNum
#         fields = ["mobile", "price", "level", "status"]
#
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         for name, field in self.fields.items():
#             field.widget.attrs = {
#                 'class': 'form-control',
#                 'placeholder': '请输入' + field.label,
#             }
#
#     def clean_mobile(self):
#         mobile = self.cleaned_data.get('mobile')
#         if len(mobile) != 11:
#             # 验证不通过
#             raise ValidationError('格式错误')
#         if PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=mobile).exists():
#             raise forms.ValidationError("该手机号码已存在。")
#         return mobile


def pretty_add(request):
    """添加靓号"""
    if request.method == "GET":
        model = PrettyNumForm()
        return render(request, "pretty_add.html", {"model": model})

    model = PrettyNumForm(data=request.POST)
    if model.is_valid():
        model.save()
        return redirect(reverse("pretty_list"))
    return render(request, 'pretty_add.html', {"model": model})


def pretty_edit(request, id):
    """编辑靓号"""
    model = PrettyNum.objects.filter(id=id).first()
    if request.method == "GET":
        """
        ufrom = PrettyEditNumForm(instance=model)   手机号码不能修改
        ufrom = PrettyNumForm(instance=model)  全部可以编辑
        """
        ufrom = PrettyEditNumForm(instance=model)
        return render(request, "pretty_edit.html", {"model": ufrom})

    ufrom = PrettyEditNumForm(data=request.POST, instance=model)
    if ufrom.is_valid():
        ufrom.save()
        return redirect(reverse("pretty_list"))

    return render(request, 'pretty_edit.html', {"model": model})


def pretty_del(request, id):
    """删除靓号"""
    PrettyNum.objects.filter(id=id).delete()
    return redirect(reverse("pretty_list"))

